<?php
/**
 * Created by PhpStorm.
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 7/2/16
 * Time: 11:00
 */

namespace Test;

class BaseTest {
    protected $_request  = null;
    protected $_response = null;
    protected $_api = 'Index/index';

    const SECRET_KEY = 'secret@9maibei.com';

    public function setRequest(array $request = array()) {
        $request['sign'] = $this->genSign($request);
        $this->_request = json_encode($request);
    }

    function genSign(array $param) {
        //0. 删除原数据中自带的sign值,防止干扰计算结果
        unset($param['sign']);

        //1. 按key由a到z排序
        ksort($param);

        foreach ($param as $key => $value) {
            if (is_array($value)) {
                $param[$key] = $this->genSign($value);
            }
        }

        //2. 生成以&符链接的key=value形式的字符串
        $paramString = urldecode(http_build_query($param));

        //3. 拼接我们的服务秘钥，并md5加密
        $sign = md5($paramString . self::SECRET_KEY);

        echo "string:" . $paramString, "\n", "param:", var_export($param), "sign:", $sign, "\n\n";

        return $sign;
    }

    public function getRequest() {
        return $this->_request;
    }

    public function setResponse($response=null) {
        $this->_response = $response;
    }

    public function getResponse() {
        return $this->_response;
    }

    public function setApi($action=null) {
        if (!is_null($action)) {
            $this->_api = $action;
        }
    }

    public function getUrl() {
        return '';
    }

    public function post() {
        $header = array('Content-type: application/json');//定义content-type为json
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $this->getUrl());//设置链接
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置是否返回信息
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//设置HTTP头
        curl_setopt($ch, CURLOPT_POST, 1);//设置为POST方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->getRequest());//POST数据
        $this->_response = curl_exec($ch);//接收返回信息
        if(curl_errno($ch)){//出错则显示错误信息
            print curl_error($ch);
        }
        curl_close($ch); //关闭curl链接

        return $this->_response;
    }
}
